use eframe::egui::{Color32, Stroke, Ui};
use egui_plot::{BoxElem, BoxPlot, BoxSpread, Legend, Plot};
use rand::Rng;

pub fn draw_kline_chart(ui: &mut Ui) {
    candlestick_chart(ui);
}

fn candlestick_chart(ui: &mut Ui) {
    let red = Color32::from_rgb(255, 0, 0);
    let green = Color32::from_rgb(0, 255, 0);

    // 生成随机数据
    let data = generate_random_box_plot_data(50, red, green);

    let plot = Plot::new("candlestick chart")
        .legend(Legend::default())
        .view_aspect(2.0);

    plot.show(ui, |plot_ui| {
        plot_ui.box_plot(data);
    });
}

fn generate_random_box_plot_data(count: usize, red: Color32, green: Color32) -> BoxPlot {
    let mut rng = rand::thread_rng();
    let mut data = Vec::with_capacity(count);

    for i in 0..count {
        let o: f64 = rng.gen_range(1.0..100.0);
        let c: f64 = rng.gen_range(1.0..100.0);
        let h: f64 = o.max(c) + rng.gen_range(0.0..10.0);
        let l: f64 = o.min(c) - rng.gen_range(0.0..10.0);

        let color = if c >= o { green } else { red };
        let elem = BoxElem::new(i as f64, BoxSpread::new(l, o, c, c, h))
            .whisker_width(0.0)
            .fill(color)
            .stroke(Stroke::new(2.0, color));

        data.push(elem);
    }

    BoxPlot::new(data)
}
